//
//  main.c
//  ADT
//
//  Created by chenyh on 2021/1/20.
//

#include <stdio.h>
#include <stdlib.h>
#include "list.h"
#include <string.h>
/**
 使用接口
 创建一个List类型的变量
 创建一个Item类型的变量
 初始化链表为空
 当链表未满且有输入时：
    把输入读取到Item类型的变量中
    在链表末尾添加项
 访问链表中的每个项并显示他们
 */
void showmovies(Item item);
char * s_gets(char *st,int n);
int main(int argc, const char * argv[]) {
    List movies;
    Item temp;
    // 初始化
    InitializeList(&movies);
    if (ListIsFull(&movies)) {
        fprintf(stderr, "No memory availi\able! Bye!\n");
        exit(1);
    }
    // 获取用户输入并存储
    puts("Enter first movie title:");
    while (s_gets(temp.title, TSIZE) != NULL && temp.title[0] != '\0') {
        puts("Enter your rating <0-10>:");
        scanf("%d",&temp.rating);
        while (getchar() != '\n') {
            continue;
        }
        if (AddItem(temp, &movies) == false) {
            fprintf(stderr, "Problem allocating memory\n");
            break;
        }
        if (ListIsFull(&movies)) {
            puts("The list is now full.");
            break;
        }
        puts("Enter next movie title (empty line to stop):");
    }
    // 显示
    
    if (ListIsEmpty(&movies)) {
        printf("No data entered. ");
    }else {
        printf("Here is the movie list: \n");
        Traverse(&movies, showmovies);
    }
    printf("You entered %d movies.\n",ListItemCount(&movies));
    
    // 清理
    EmptyTheList(&movies);
    printf("Bye!\n");
    return 0;
}
char * s_gets(char * st,int n)
{
    char * ret_val;
    char * find;
    ret_val = fgets(st, n, stdin);
    if (ret_val) {
        find = strchr(st, '\n'); //strchar从st从查找'\n'
        if (find) {
            *find = '\0';
        }else
            while (getchar() != '\n')
                continue;
    }
    return ret_val;
}

void showmovies(Item item) {
    printf("Movie: %s Rating: %d\n",item.title,item.rating);
}
